package framework.basedao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by lliu on 2015/11/7.
 */
public class HibernateCrudDao<E, I extends Serializable> extends HibernateDaoSupport implements CrudDao<E, I> {

    protected Class<? extends E> clazz;

    public HibernateCrudDao(Class<? extends E> clazz) {
        this.clazz = clazz;
    }

    public HibernateCrudDao() {
        this.clazz = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public void flush() {
        this.getHibernateTemplate().flush();
    }

    public void evit(E o) {
        Assert.notNull(o);
        this.getHibernateTemplate().evict(o);
    }

    public void save(E o) {
        Assert.notNull(o);
        this.getHibernateTemplate().save(o);
    }

    public void delete(I id) {
        Assert.notNull(id);
        this.delete(this.get(id));
    }

    public void delete(E o) {
        Assert.notNull(o);
        this.getHibernateTemplate().delete(o);
    }

    public E get(I id) {
        Assert.notNull(id);
        return this.getHibernateTemplate().get(this.clazz, id);
    }

    public E load(I id) {
        Assert.notNull(id);
        return this.getHibernateTemplate().load(this.clazz, id);
    }

    @Override
    public List<E> loadAll() {
        return (List<E>) this.getHibernateTemplate().loadAll(this.clazz);
    }

    public void update(E o) {
        Assert.notNull(o);
        this.getHibernateTemplate().update(o);
    }


    public E refresh(E o) {
        Assert.notNull(o);
        this.getHibernateTemplate().refresh(o);
        return o;
    }


    @Autowired
    public void setSessionFactoryOverride(final SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

}
